<template>
  <el-form ref="form" :model="form" :rules="rules" :hide-required-asterisk="true" label-position="left" style="margin:0 20px;">
    <el-form-item :label="$t('对象名称')" :label-width="formLabelWidth" prop="name" @input="updateView($event)">
      <el-input v-emoji size='small' v-model="form.name" autocomplete="off" ref="name"></el-input>
    </el-form-item>
    <el-form-item :label="$t('描述')" :label-width="formLabelWidth">
      <el-input v-emoji size='small' type="textarea" ref="desc" @keydown.native="handleKeyCode($event)" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('请输入内容')" v-model="form.desc">
      </el-input>
    </el-form-item>

    <!--    添加对象页面-->
    <div>
      <el-button type="success" @click="add_addr" size="small" style="margin-bottom:10px;" class="addObjeck">{{$t('添加对象')}}</el-button>
      <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加对象')" :v-if="dialogAddrFormVisible" :visible.sync="dialogAddrFormVisible" width="800px" append-to-body>
        <el-table size='mini' ref="multipleTable" :data="addr_list_info" tooltip-effect="dark" header-align="center" :align="'center'" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align="center" :selectable='selectableRow' type="selection" width="55">
          </el-table-column>
          <el-table-column align="center" prop="strPhysicsName" :label="$t('接口名称')" width="80">
          </el-table-column>
          <el-table-column align="center" prop="name" :label="$t('别名')" width="80">
            <template slot-scope="scope">
              <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name"></tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="enPortMode" :label="$t('模式')" width="100" :formatter="handel_enPortMode">
          </el-table-column>
          <el-table-column align="center" prop="ipv4" :label="$t('IPv4/子网掩码')" min-width="150">
            <template slot-scope="scope">
              <tooltip :html="classMapShow(scope.row, ';<br/>')" :content="classMapShow(scope.row, ',')" class="wid190" :refName="scope.row.name"></tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="ipv6" :label="$t('IPv6/前缀')" width="100">
            <template slot-scope="scope">
              <tooltip :html="handel_ipv6_array(scope.row)" :content="handel_ipv6_array(scope.row)" class="wid190" :refName="handel_ipv6_array(scope.row)">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="bLinkStatus" :label="$t('链路状态')" width="90" :formatter="bLinkStatus">
          </el-table-column>
          <el-table-column align="center" prop="bPortStatus" :label="$t('状态')" width="80" :formatter="bPortStatus">
          </el-table-column>
          <el-table-column align="center" prop="iMtu" :label="$t('Mtu值')" width="80">
          </el-table-column>
          <el-table-column align="center" prop="bandwidth" :label="$t('速率')" width="80">
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="add_addr_submit">{{$t('确 定')}}</el-button>
          <el-button @click="dialogAddrFormVisible = false">{{$t('取 消')}}</el-button>
        </div>
      </el-dialog>

      <el-table size='mini' :data="form.iface_array" stripe border style="width: 100%">
        <el-table-column align="center" prop='name' :label="$t('名称')">
          <template slot-scope="scope">
            <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" :label="$t('操作')" width="120">
          <template slot-scope="scope">
            <el-button @click.native.prevent="deleteRow(scope.$index, form.iface_array, ifaceArrayList)" :class="'del' + scope.$index" type="danger" plain size="mini">
              {{$t('删除')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-form>

</template>

<script>
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  inject: ['reload'],
  props: [
    'dialogFormVisible',
    'type_info',
    'edit_form'
  ],
  name: 'SafeEdit',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    return {
      old_name: {},
      old_desc: '',
      addr_list_info: [],
      addrSelection: [],
      ifaceArrayList: [],
      form: {
        name: '',
        desc: '',
        iface_array: []
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      },
      formLabelWidth: '20%',
      dialogAddrFormVisible: false
    }
  },
  mounted () {
    this.$nextTick(() => {
      const data = ['name']
      const textdata = ['desc']
      inputClass(this.$refs, data)
      texttextClass(this.$refs, textdata)
    })
  },
  watch: {
    edit_form: {
      handler (val) {
        if (this.type_info === '编辑') {
          this.form = Object.assign(this.form, val)
          this.old_name = val.name
          this.old_desc = val.desc
          this.form.iface_array = []
          this.ifaceArrayList = []
          val.iface.split(',').forEach((index) => {
            this.form.iface_array.push({ 'name': index })
            this.ifaceArrayList.push(index)
          })
        }
      },
      immediate: true
    },
    'dialogAddrFormVisible': {
      handler (newVal) {
        if (newVal === true) {
          this.addr_list_info = []
          this.addrSelection = []
          getPhysicalApiArray().then(response => {
            this.addr_list_info = response.info
            this.$nextTick(() => {
              if (this.form.iface_array && this.form.iface_array.length > 0) {
                for (let item of this.addr_list_info) {
                  if (this.ifaceArrayList.includes(item.strPhysicsName)) {
                    this.$refs.multipleTable.toggleRowSelection(item, true)
                  }
                }
              }
            })
          })
        }
      },
      immediate: true
    },
    'form.desc': {
      handler (newVal) {
        if (newVal) {
          this.form.desc = newVal.replace(/[\r\n]/g, '')
        }
      },
      immediate: true
    }
  },
  methods: {
    add_addr_submit () {
      this.form.iface_array = []
      this.ifaceArrayList = []
      this.addrSelection.forEach((values, index) => {
        this.form.iface_array.push({ 'name': values.strPhysicsName })
        this.ifaceArrayList.push(values.strPhysicsName)
      })
      this.dialogAddrFormVisible = false
    },
    handleSelectionChange (val) {
      this.addrSelection = val
    },
    handel_ipv4_array (row) {
      if (row.ipv4) {
        let test = ''
        row.ipv4.forEach((item, index, array) => {
          if (item.cPortIpv4 !== '') {
            test += item.cPortIpv4 + '/'
          }
          if (item.cPortNetmask !== '') {
            test += item.cPortNetmask
          }
        })
        return test
      }
    },
    handel_ipv6_array (row) {
      if (row.ipv4) {
        let test = ''
        row.ipv6.forEach((item, index, array) => {
          if (item.cPortIpv6 !== '') {
            test += item.cPortIpv6 + '/'
          }
          if (item.cDevIpv6Prefix !== '') {
            test += item.cDevIpv6Prefix
          }
        })
        return test
      }
    },
    bPortStatus (row) {
      switch (row.bPortStatus) {
        case 'up':
          return this.$t('开启')
        case 'down':
          return this.$t('关闭')
      }
    },
    handel_enPortMode (row) {
      switch (row.enPortMode) {
        case 0:
          return this.$t('路由模式')
        case 1:
          return this.$t('透明模式')
        case 2:
          return this.$t('聚合模式')
        case 3:
          return this.$t('虚拟线模式')
      }
    },
    bLinkStatus (row) {
      switch (row.bLinkStatus) {
        case 0:
          return 'down'
        case 1:
          return 'up'
      }
    },
    selectableRow (row) {
      return row.enPortMode === 0
    },
    weekdaysForm (value) {
      this.form.weekdays = value
    },
    monthdaysForm (value) {
      this.form.monthdays = value
    },
    inputChange (type) {
      if (type === 'account') {
        this.form.account = this.form.account.replace(/([\u4e00-\u9fa5])|(\s)|[^\d\w]/g, '')
      } else {
        this.form.mobile = this.form.mobile.replace(/[^\d]/g, '')
      }
    },
    // 发送form表单数据到父组件
    send_form () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let childForm = {}
          childForm = JSON.parse(JSON.stringify(this.form))
          if (!childForm.name) {
            this.$messages.error(this.$t('请输入名称'))
            return
          }
          if (childForm.iface_array && childForm.iface_array.length > 0) {
            if (this.type_info === '编辑') {
              childForm.old_name = this.old_name
            }
            let iface = ''
            childForm.iface_array.forEach((item, index) => {
              if (index !== childForm.iface_array.length - 1) {
                iface += item.name + ','
              } else {
                iface += item.name
              }
            })
            childForm.iface = iface
            this.$emit('childForm', childForm)
          } else {
            this.$messages.error(this.$t('对象不能为空'))
          }
        }
      })
    },
    updateView (e) {
      this.$forceUpdate()
    },
    add_addr () {
      this.dialogAddrFormVisible = true
    },
    backParent () {
      this.$emit('quxiao', false)
    },
    deleteRow (index, rows, rowList) {
      rows.splice(index, 1)
      rowList.splice(index, 1)
    },
    classMapShow (data, str) {
      let reStr = ''
      if (data.ipv4) {
        data.ipv4.forEach((item, index, array) => {
          if (index < 1 && str === ',') {
            reStr += (item.cPortIpv4 ? item.cPortIpv4 : '') + '/' + (item.cPortNetmask ? item.cPortNetmask : '')
          } else if (str === ',') {
            reStr += str + (item.cPortIpv4 ? item.cPortIpv4 : '') + '/' + (item.cPortNetmask ? item.cPortNetmask : '')
          } else {
            reStr += (item.cPortIpv4 ? item.cPortIpv4 : '') + '/' + (item.cPortNetmask ? item.cPortNetmask : '') + str
          }
        })
        return reStr
      }
    },
    close () {
      this.addr_list_info = []
      this.addrSelection = []
      this.form = {
        name: '',
        desc: '',
        iface_array: []
      }
      this.ifaceArrayList = []
      this.old_name = {}
      this.old_desc = ''
      this.$refs.form.resetFields()
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}

.circle {
  padding: 5px;
}
</style>
